package com.web.music.portal.mvc;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.servlet.mvc.SimpleFormController;

import com.web.music.interfaces.SecurityController;
import com.web.music.interfaces.UserService;
import com.web.music.model.ChangePasswordForm;
import com.web.music.model.User;

public class ChangePasswordFormController extends SimpleFormController {
	
	private UserService userService;
	private SecurityController securityController; 

	public ChangePasswordFormController() {
		setCommandClass(ChangePasswordForm.class);
		setSessionForm(true);
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request) throws Exception {
		User user = securityController.getSessionUser(request);
		if (!isFormSubmission(request)){	
			String idString = request.getParameter("id");
			if (user != null && user.getIsAdmin().equals("Y") && idString != null && !idString.equals("")) {
				long id = Long.parseLong(request.getParameter("id"));
				user = userService.getById(id);
			}			
		}
		ChangePasswordForm form = new ChangePasswordForm();
		form.setUser(user);
		return form;
	}

	@Override
	protected void doSubmitAction(Object object) throws Exception {
		ChangePasswordForm form = (ChangePasswordForm) object;
		User user = form.getUser();
		user.setPassword(form.getPassword());
		userService.save(user);
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public SecurityController getSecurityController() {
		return securityController;
	}

	public void setSecurityController(
			SecurityController authorizableController) {
		this.securityController = authorizableController;
	}
	
}
